package servlet;

import model.User;
import service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.MultipartConfig;
import java.io.IOException;
import java.io.File;
import java.util.Date;

@WebServlet(name = "admin_add", urlPatterns = "/admin/admin_add")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024, // 1 MB
        maxFileSize = 1024 * 1024 * 10,  // 10 MB
        maxRequestSize = 1024 * 1024 * 15 // 15 MB
)
public class AdminAdminAddServlet extends HttpServlet {
    private UserService userService = new UserService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求编码
        request.setCharacterEncoding("UTF-8");

        // 获取表单数据
        String nickname = request.getParameter("nickname");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        boolean isAdmin = "1".equals(request.getParameter("is_admin"));

        // 处理头像上传
        String avatarPath = "/picture/avatar.png"; // 默认头像
        Part avatarPart = request.getPart("avatar");
        if (avatarPart != null && avatarPart.getSize() > 0) {
            String fileName = new Date().getTime() + getFileExtension(avatarPart);
            String uploadPath = getServletContext().getRealPath("/picture");
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            avatarPart.write(uploadPath + File.separator + fileName);
            avatarPath = "/picture/" + fileName;
        }

        // 创建用户对象并设置属性
        User user = new User();
        user.setNickname(nickname);
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setAvatar(avatarPath);
        user.setAdmin(isAdmin);
        System.out.println(isAdmin);
        // 注册用户
        boolean isSuccess = userService.register(user);
        String message = userService.getRegisterResultMessage(isSuccess, username, email);
        request.setAttribute("msg", message);

        if (isSuccess) {
            response.sendRedirect(request.getContextPath() + "/admin/user_list" );
        } else {
            request.getRequestDispatcher("/user_add.jsp").forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 处理 GET 请求，跳转到注册页面
//        request.getRequestDispatcher("/user_register.jsp").forward(request, response);
        doPost(request, response);
    }

    private String getFileExtension(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] tokens = contentDisp.split(";");
        for (String token : tokens) {
            if (token.trim().startsWith("filename")) {
                String fileName = token.substring(token.indexOf("=") + 2, token.length() - 1);
                int dotIndex = fileName.lastIndexOf(".");
                return dotIndex > 0 ? fileName.substring(dotIndex) : "";
            }
        }
        return "";
    }
}